//
//  sessionVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/7/19.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "sessionVC.h"
#import "thirdPersonVC.h"
#import "LSManyPeopleListVC.h"
#import "LSHongBaoVC.h"
#import "ForgetPassWord.h"
#import "LSRechargeVC.h"

#import "LSReceiveListVC.h"

@interface sessionVC ()<UIActionSheetDelegate,RCPluginBoardViewDelegate,RCMessageCellDelegate>

@property (strong, nonatomic)NSMutableDictionary * HBDict;
@property (strong, nonatomic)LSReceiveListVC * LSReceiveList;
@end

@implementation sessionVC

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    
    //红包通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendHongBaoMessage:) name:@"sendHongBao" object:nil];
    
    //设置支付密码
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPayPass) name:@"setPayPass" object:nil];
    
    //充值
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RechargePrice) name:@"RechargePrice" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    //右item
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightBtn) image:@"设置-消息" highImage:@"设置-消息"];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    if (self.tlzDict && self.style) {
    
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"红包-1"] title:@"红包" tag:101];
    [self registerClass:[LSSimpleMessageCell class] forMessageClass:[LSSimpleMessageVC class]];
    };

    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

-(void)rightBtn{
    
    if (!self.tlzDict && !self.style) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"当前操作"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"清空聊天消息", nil];
        
        [actionSheet showInView:self.view];
        
    }else if(self.style && [[USER_DEFAULTS objectForKey:@"account"] isEqualToString:self.tlzDict[@"creatorId"]]){
    
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"当前操作"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"管理成员",@"清空聊天消息",@"退出当前讨论组", nil];
        
        [actionSheet showInView:self.view];
    
    }else if (self.style && ![[USER_DEFAULTS objectForKey:@"account"] isEqualToString:self.tlzDict[@"creatorId"]]){
    
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"当前操作"
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"查看成员",@"清空聊天消息",@"退出当前讨论组", nil];
        
        
        [actionSheet showInView:self.view];
        
    
    }
    
    
}

#pragma mark - 发送红包按钮
-(void)pluginBoardView:(RCPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag{

    
    LSHongBaoVC * LSHongBao = [[LSHongBaoVC alloc]init];

    switch (tag) {
        case 101: {
            LSHongBao.tlzDict = self.tlzDict;
            [self presentViewController:LSHongBao animated:YES completion:nil];
            
        } break;
        default:
            [super pluginBoardView:pluginBoardView clickedItemWithTag:tag];
            break;
    }

}

#pragma mark - 右上角按钮
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (!self.tlzDict && !self.style) {
        switch (buttonIndex) {
                
            case 0:
            {
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:self.targetId];
                
                [self.conversationDataRepository removeAllObjects];
                [self.conversationMessageCollectionView reloadData];
                
            }
                break;
                
                
            case 1:
                // 取消
                break;
                
            default:
                break;
        }
        
    }else{
    
    if (self.style && [[USER_DEFAULTS objectForKey:@"account"] isEqualToString:self.tlzDict[@"creatorId"]]) {
        LSManyPeopleListVC * LSManyPeopleList = [[LSManyPeopleListVC alloc]init];
        switch (buttonIndex) {
                
            case 0:
            {
                LSManyPeopleList.discussionId = self.tlzDict[@"discussionId"];
                LSManyPeopleList.tlzDict = self.tlzDict;
                [self.navigationController pushViewController:LSManyPeopleList animated:YES];
            }
                break;
                
            case 1:
            {
                [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:self.targetId];
                
                [self.conversationDataRepository removeAllObjects];
                [self.conversationMessageCollectionView reloadData];
                
            }
                break;
                
            case 2:
            {
                [[RCIMClient sharedRCIMClient] quitDiscussion:self.tlzDict[@"discussionId"] success:^(RCDiscussion *discussion) {
                    

                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        
                    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"已退出当前讨论组!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alert show];
                    });
                    NSLog(@"退出讨论组");
                    
                } error:^(RCErrorCode status) {
                    
                   NSLog(@"create discussion Failed &gt; %ld!", (long)status);
                    
                }];
            }
                break;
                
                
            case 3:
                // 取消
                break;
                
            default:
                break;
        }
    
    
    }else if (self.style && ![[USER_DEFAULTS objectForKey:@"account"] isEqualToString:self.tlzDict[@"creatorId"]]){
        LSManyPeopleListVC * LSManyPeopleList = [[LSManyPeopleListVC alloc]init];
    switch (buttonIndex) {
            
        case 0:
        {
            [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:self.targetId];
            
            LSManyPeopleList.tlzDict = self.tlzDict;
            [self.navigationController pushViewController:LSManyPeopleList animated:YES];
            
        }
            break;
            
        case 1:
        {
            [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:self.targetId];
            
            [self.conversationDataRepository removeAllObjects];
            [self.conversationMessageCollectionView reloadData];
            
        }
            break;
            
        case 2:
        {
            [[RCIMClient sharedRCIMClient] quitDiscussion:self.discussionId success:^(RCDiscussion *discussion) {
                
                
                NSMutableDictionary * dictData = [NSMutableDictionary dictionary];
                
                // 退出讨论组
                
                [dictData setValue:allConstMemberToken forKey:@"token"];
                [dictData setValue:self.discussionId forKey:@"groupId"];
                [dictData setValue:allConstMemberid forKey:@"userId"];
                
                NSString *str = @"outCircle_app_social.im.lensum?";
                
                [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
                    
                    NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                    
                    if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                        
                        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"已退出当前讨论组!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                        
                        [self.navigationController popToRootViewControllerAnimated:YES];

                        
                    }
                    
                    
                } failure:^(NSError *error) {
                    [self showSingleIconBubble:@"网络连接错误"];
                    
                }];
                
            } error:^(RCErrorCode status) {
                
                NSLog(@"create discussion Failed &gt; %ld!", (long)status);
                
            }];
        }
            break;

            
        case 3:
            // 取消
            break;
            
        default:
            break;
    }
        
    }
        
    }
}

/**
 *  点击头像事件
 *
 *  @param userId 用户的ID
 */
- (void)didTapCellPortrait:(NSString *)userId{
    
    if ([[USER_DEFAULTS objectForKey:@"account"] isEqualToString:userId]) {
        
        NSMutableArray *photos = [NSMutableArray array];
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[USER_DEFAULTS objectForKey:@"headPhoto"]];
//        photo.srcImageView = self.headView.imgStr;
        [photos addObject:photo];
        browser.photos = photos;
        
        [browser show];
        
    }else{
    
    thirdPersonVC * thirdPerson = [[thirdPersonVC alloc]init];
    thirdPerson.account = userId;

    [self.navigationController pushViewController:thirdPerson animated:YES];
        
    }

    NSLog(@"----------userId:%@",userId);

}

#pragma mark - 点击红包
- (void)didTapMessageCell:(RCMessageModel *)model{
    
    [self showRoundProgressWithTitle:@"请稍后..."];
    
   RCMessage * message = [[RCIMClient sharedRCIMClient] getMessage:model.messageId];
    
    if ([model.content isKindOfClass:[LSSimpleMessageVC class]]) {
        
        NSMutableDictionary * mutableParams = [NSMutableDictionary dictionary];
        mutableParams[@"hairUserId"] = model.senderUserId;
        mutableParams[@"token"] = allConstMemberToken;
        mutableParams[@"messageId"] = message.messageUId;
        mutableParams[@"type"] = @(1);
        mutableParams[@"userId"] = allConstMemberid;
        
        NSString *str = @"robRed_app_social.im.lensum?";
        
        [LSHttpTool sendHttpData:str params:mutableParams success:^(id responseObject) {
            
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
            
            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                
                NSLog(@"**********%@***********",[dicInfo objectForKey:@"msg"]);
                
                _LSReceiveList = [[LSReceiveListVC alloc]init];
                
                _LSReceiveList.dataDict = [dicInfo copy];
                
                _LSReceiveList.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                
                _LSReceiveList.view.hidden = YES;
                
                [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{

                        [self presentViewController:_LSReceiveList animated:YES completion:^{
                            _LSReceiveList.view.transform = CGAffineTransformMakeScale(0.1f, 0.1f);//将要显示的view按照正常比例显示出来
                            [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
                            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; //InOut 表示进入和出去时都启动动画
                            [UIView setAnimationDuration:0.6f];//动画时间
                            _LSReceiveList.view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
                            [UIView commitAnimations]; //启动动画
                            _LSReceiveList.view.hidden = NO;
                        }];

                } completion:^(BOOL finished) {
                    
                }];
                
            }else{
                
                if ([[dicInfo objectForKey:@"result"] integerValue] == 2) {
                    
                    if ([[dicInfo objectForKey:@"msg"] isEqualToString:@"红包已经被抢完"] || [[dicInfo objectForKey:@"msg"] isEqualToString:@"已经领取过"]) {
                        
//                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicInfo objectForKey:@"msg"] delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
//                        [alert show];
                        
                        _LSReceiveList = [[LSReceiveListVC alloc]init];
                        
                        _LSReceiveList.dataDict = [dicInfo copy];
                        
                        _LSReceiveList.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                        
                        _LSReceiveList.view.hidden = YES;
                        

                            
                [self presentViewController:_LSReceiveList animated:YES completion:^{
                                
                    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                        _LSReceiveList.view.transform = CGAffineTransformMakeScale(0.3f, 0.3f);//将要显示的view按照正常比例显示出来
                        [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
                        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; //InOut 表示进入和出去时都启动动画
                        [UIView setAnimationDuration:0.5f];//动画时间
                        _LSReceiveList.view.transform=CGAffineTransformMakeScale(1.0f, 1.0f);//先让要显示的view最小直至消失
                        [UIView commitAnimations]; //启动动画
                        _LSReceiveList.view.hidden = NO;
                        
                    } completion:^(BOOL finished) {
                        
                    }];
                }];
                        
 
                        
                    }else if([[dicInfo objectForKey:@"msg"] isEqualToString:@"这个信息id不存在"]){
                    
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[dicInfo objectForKey:@"msg"] delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
                        [alert show];
                    
                    }
                }
            
            
            }
            [self hideBubble];
            
        } failure:^(NSError *error) {
            [self hideBubble];

            [self showSingleIconBubble:@"网络连接错误"];
            
        }];
            NSLog(@"**********点击了自定义消息*********");
            NSLog(@"全局唯一id:%@",model.messageUId);
            NSLog(@"数据库id:%ld",model.messageId);
            NSLog(@"目标会话id:%@",model.targetId);
            NSLog(@"发送者id:%@",model.senderUserId);
            NSLog(@"消息类型名:%@",model.objectName);
    
    }

}

//- (RCMessage *)willAppendAndDisplayMessage:(RCMessage *)message{
//    
//    if ([message.content isKindOfClass:[LSSimpleMessageVC class]]) {
//        
//        long i;
//        
//        if (message.messageId == 2) {
//            
//            i = message.messageId;
//            
//        }else{
//        
//            i = message.messageId;
//        
//        }
//      NSArray * arr = [[RCIMClient sharedRCIMClient] getLatestMessages:ConversationType_DISCUSSION targetId:message.targetId count:1];
//        
//        
//      RCConversation * RCConver =   [[RCIMClient sharedRCIMClient] getConversation:ConversationType_DISCUSSION targetId:message.targetId];
//        
//        NSLog(@"自定义消息全局唯一id:%@",message.messageUId);
//        NSLog(@"数据库id:%ld",message.messageId);
//
//        NSMutableDictionary * mutableParams = [NSMutableDictionary dictionary];
//        mutableParams[@"redId"] = self.HBDict[@"resID"];
//        mutableParams[@"token"] = token;
//        mutableParams[@"messageId"] = message.messageUId;
//        
//        NSString *str = @"setMessageId_app_social.im.lensum?";
//        
//        [LSHttpTool sendHttpData:str params:mutableParams success:^(id responseObject) {
//            
//            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//            
//            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
//                
//                NSLog(@"**********%@***********",[dicInfo objectForKey:@"msg"]);
//                
//            }
//            
//            
//        } failure:^(NSError *error) {
//            

//            
//        }];
//   
//
//    }
//
//    return message;
//
//}

#pragma mark - 自定义会话展示

-(RCMessageBaseCell *)rcConversationCollectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RCMessageModel *model = self.conversationDataRepository[indexPath.row];
    NSString * cellIndentifier=@"SimpleMessageCell";
    RCMessageBaseCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier           forIndexPath:indexPath];
    [cell setDataModel:model];
    
    if ([RCMessageContent isMemberOfClass:[LSSimpleMessageVC class]]) {

        [cell setDelegate:self];
        
    }
    return cell;
}

-(CGSize)rcConversationCollectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //返回自定义cell的实际高度（这里请返回消息的实际大小）
    return CGSizeMake(300, 180);
}

-(void)leftBarButtonItemClick{
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    
     [super leftBarButtonItemPressed:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 发送红包自定义消息
-(void)sendHongBaoMessage:(NSNotification *)notification{
    
//    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionaryWithDictionary:notification.userInfo];
//    
//    self.HBDict = muDicParameters;
//
//        LSSimpleMessageVC * LSSimpleMessage = [[LSSimpleMessageVC alloc]init];
//        
//        LSSimpleMessage.content = muDicParameters[@"text"];
//    
//    [[RCIM sharedRCIM] sendMessage:ConversationType_DISCUSSION targetId:self.targetId content:LSSimpleMessage pushContent:muDicParameters[@"text"] pushData:muDicParameters[@"text"] success:^(long messageId) {
//        
//       RCMessage * message = [[RCIMClient sharedRCIMClient] getMessage:messageId];
//        long strId;
//        NSString * strUid;
//        strId = message.messageId;
//        strUid = message.messageUId;
//        
//    } error:^(RCErrorCode nErrorCode, long messageId) {
//        
//    }];
//
////        [self sendMessage:LSSimpleMessage pushContent:@"你收到了一条红包消息"];
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendHongBao" object:nil];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.conversationMessageCollectionView reloadData];
        
    });
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendHongBao" object:nil];
}

#pragma mark - 设置支付密码
-(void)setPayPass{

    UIStoryboard *LoginAndRegister = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ForgetPassWord *ForgetPassWord = [LoginAndRegister instantiateViewControllerWithIdentifier:@"forgetpassword"];
    ForgetPassWord.titleStr = @"修改支付密码";
    [self.navigationController pushViewController:ForgetPassWord animated:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"setPayPass" object:nil];
}

#pragma mark - 充值
-(void)RechargePrice{

    LSRechargeVC * LSRecharge = [[LSRechargeVC alloc]init];
    [self.navigationController pushViewController:LSRecharge animated:YES];
    
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RechargePrice" object:nil];
    
}
@end
